package com.lin.order.Service.impl;



import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClient;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
import com.lin.order.Bean.Order;
import com.lin.order.Service.OrderService;
import com.lin.product.Bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class orderServiceImpl implements OrderService {


    @Autowired
    DiscoveryClient discoveryClient;


    @Autowired
    RestTemplate restTemplate;

    @Override
    public Order createOrder(Long userId, Long productId) {
        Product product = getProductFromRemoteWithLoadBalancedAnnotation(productId);
        Order order = new Order();
        order.setOrderId(1L);

        // 总金额
        order.setTotalAmount(product.getPrice() * product.getNum());
        order.setUserId(userId);
        order.setNickName("xiaoming");
        order.setAddress("广东省珠海市");

        // 远程查询
        order.setProductList(Arrays.asList(product));
        return order;
    }

    private Product getProductFromRemote(Long productId) {
        //1. 找到商品服务的所有地址
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");

        ServiceInstance serviceInstance = instances.get(0);

        String url = "http://"+serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/product/" + productId;
        log.info("远程请求url:{}", url);


        //2.给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }


    //使用负载均衡的方式调用网址
    private Product getProductFromRemoteWithLoadBalancedAnnotation(Long productId) {


        //然后只需要在要随时负载均衡的位置加上模块名字即可
        String url = "http://service-product/product/" + productId;
        log.info("远程请求url:{}", url);

        //2.给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
}
